package com.project.weimi.fragment;

import java.util.ArrayList;
import java.util.List;

import com.project.weimi.R;
import com.project.weimi.adapter.ShoppingAdapter;
import com.project.weimi.entity.response.ShopEntity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;

@SuppressLint("InflateParams")
public class ShoppingFragment extends BaseFragment implements OnRefreshListener {

	private SwipeRefreshLayout mSwipeRefreshWidget;
	private LinearLayoutManager mLayoutManager;
	private RecyclerView mRecyclerView;
	private ShoppingAdapter mAdapter;
	private View footerView;
	
	private LinearLayout empty;
	private TextView goshopping;

	private int lastVisibleItem;

	private TextView tv;// 页面头部显示数量
	private boolean checkAll = true;
	private LinearLayout check_all;// 全选
	private CheckBox checkbox_all;
	private TextView price;// 合计（总价）
	private TextView yuanfei;// （是否包含）运费
	private TextView total;// 结算（数量）

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				mSwipeRefreshWidget.setRefreshing(false);

				mAdapter.getList().clear();
				addList();
				break;
			case 1:
				addList();
				break;
			default:
				break;
			}

		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		// 解析布局文件
		View view = inflater.inflate(R.layout.fragment_shop, null);
		initView(view);
		return view;
	}

	private void initView(View view) {
		// TODO Auto-generated method stub
		footerView = getActivity().getLayoutInflater().inflate(R.layout.shopping_footerview, null);

		mSwipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
		mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);

		mSwipeRefreshWidget.setColorScheme(R.color.color1, R.color.color2, R.color.color3, R.color.color4);
		mSwipeRefreshWidget.setOnRefreshListener(this);

		tv = (TextView) view.findViewById(R.id.tv);
		check_all = (LinearLayout) view.findViewById(R.id.check_all);
		checkbox_all = (CheckBox) view.findViewById(R.id.checkbox_all);
		price = (TextView) view.findViewById(R.id.price);
		yuanfei = (TextView) view.findViewById(R.id.yuanfei);
		total = (TextView) view.findViewById(R.id.total);
		
		empty = (LinearLayout) view.findViewById(R.id.empty);
		goshopping = (TextView) view.findViewById(R.id.goshopping);

		mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {

			@Override
			public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
				super.onScrollStateChanged(recyclerView, newState);
				
//				Log.e("TAG", "first--" + mLayoutManager.findFirstVisibleItemPosition()
//								+ "--last--" + mLayoutManager.findLastVisibleItemPosition()
//								+ "--count--" + mAdapter.getItemCount());
				if(mAdapter.getItemCount() <= 3){
					return;
				}
				
				if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == mAdapter.getItemCount()) {
					handler.sendEmptyMessageDelayed(1, 3000);
				}
			}

			@Override
			public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
				super.onScrolled(recyclerView, dx, dy);
				lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
			}

		});

		mRecyclerView.setHasFixedSize(true);
		mLayoutManager = new LinearLayoutManager(getActivity());
		mRecyclerView.setLayoutManager(mLayoutManager);
		mRecyclerView.setItemAnimator(new DefaultItemAnimator());

		mAdapter = new ShoppingAdapter(getActivity());
		mRecyclerView.setAdapter(mAdapter);
		// setHeader(mRecyclerView);
		if(mAdapter.getList() == null || mAdapter.getList().size() <= 0){
			mRecyclerView.setVisibility(View.GONE);
			empty.setVisibility(View.VISIBLE);
		}
		
		goshopping.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				addList();
			}
		});
		

		check_all.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				checkAll = true;
				checkbox_all.setChecked(!checkbox_all.isChecked());
			}
		});
		checkbox_all.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				checkAll = true;
			}
		});
		checkbox_all.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				if (checkAll) {
					for (int i = 0; i < mAdapter.getList().size(); i++) {
						mAdapter.getList().get(i).setShop_check(isChecked);
					}

					mAdapter.notifyDataSetChanged();
				}

				itemCheckBox();
			}
		});
	}

	public void itemCheckBox() {
		checkAll = false;
		int totalNum = 0;
		int totalPrice = 0;
		for (int i = 0; i < mAdapter.getList().size(); i++) {
			if (mAdapter.getList().get(i).getShop_check()) {
				totalNum++;
				
				if(!TextUtils.isEmpty(mAdapter.getList().get(i).getShop_price_xian())
						&& !TextUtils.equals(mAdapter.getList().get(i).getShop_price_xian(), "null")
						&& !TextUtils.equals(mAdapter.getList().get(i).getShop_price_xian(), "0")){
					
					totalPrice = totalPrice + (Integer.valueOf(mAdapter.getList().get(i).getShop_num())
							* Integer.valueOf(mAdapter.getList().get(i).getShop_price_xian()));
				} else {
					totalPrice = totalPrice + (Integer.valueOf(mAdapter.getList().get(i).getShop_num())
							* Integer.valueOf(mAdapter.getList().get(i).getShop_price_normal()));
				}
			}
		}
		if (totalNum != mAdapter.getList().size() || mAdapter.getList().size() == 0) {
			checkbox_all.setChecked(false);
		} else {
			checkbox_all.setChecked(true);
		}
		
		price.setText("¥" + totalPrice);
		total.setText("结算(" + totalNum + ")");
		tv.setText("购物车("+ mAdapter.getList().size() +")");
	}

	/** 添加列表头 */
	private void setHeader(RecyclerView view) {
		View header = LayoutInflater.from(getActivity()).inflate(R.layout.shopping_headerview, view, false);
		mAdapter.setHeaderView(header);
	}

	/** 数据适配 */
	private void addList() {
		empty.setVisibility(View.GONE);
		mRecyclerView.setVisibility(View.VISIBLE);
		
		List<ShopEntity> list = getList();
		mAdapter.getList().addAll(list);
		mAdapter.notifyDataSetChanged();
		tv.setText("购物车("+ mAdapter.getList().size() +")");
	}

	/** 获取数据 */
	private List<ShopEntity> getList() {
		List<ShopEntity> list = new ArrayList<ShopEntity>();
		ShopEntity shopEntity = null;
		int size = mAdapter.getList().size();
		// int lastPosition = size > 0 ? mAdapter.getList().get(size - 1) : 0;
		for (int i = 1; i < 11; i++) {
			if(i % 3 == 0){
				shopEntity = new ShopEntity(1, false, R.drawable.icon_item1, "唯蜜" + (size + i), "颜色:白色;尺码:2XL", "0", "128",
						"1");
			} else {
				
				shopEntity = new ShopEntity(1, false, R.drawable.icon_item1, "唯蜜" + (size + i), "颜色:白色;尺码:2XL", "59", "128",
						"1");
			}

			list.add(shopEntity);
		}
		return list;
	}

	/** 刷新列表 */
	@Override
	public void onRefresh() {
		handler.sendEmptyMessageDelayed(0, 3000);
	}

}
